<?php


namespace app\index\controller;

use app\index\model\OrderItem;
use app\index\model\Product;
use app\index\model\ProductPurHistory;
use app\index\model\StockWarehouse;
use app\index\model\User;
use app\index\model\Vendor;
use think\Exception;
use think\Loader;
use think\Request;
use think\response\Json;

class Stock extends BaseController
{
    protected $request;
    protected $validate;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=$request;
        $this->validate=Loader::validate('Stock');
    }

    public function stockOutByGoodsId(){
        $data=input('post.data/a');
        if(!isset($data['pro_id']) || !$data['pro_id']){
            return json(['code'=>1,'msg'=>'id不能为空']);
        }
        if(!isset($data['amount']) || !$data['amount']){
            return json(['code'=>1,'msg'=>'出库数量必须大于0']);
        }

        $ProductClass=new Product();
        $ProductPurHistory=new ProductPurHistory();
        $ProductClass->startTrans();
        try{
            $stock=$ProductClass->where('id',$data['pro_id'])->field('id,amount,locked_quantity,selling_price,vendor_id')->find();
            if(round(($stock['amount']-$stock['locked_quantity']),2)<$data['amount']){
                return json(['code'=>1,'msg'=>'剩余可出库库存不足']);
            }
            $update_stock=$stock['amount']-$data['amount'];
            $result=$ProductClass->where('id',$data['pro_id'])->update(['amount'=>$update_stock]);
            if($result===false){
                return json(['code'=>1,'msg'=>'更新库存失败']);
            }
            $ProductPurHistory->data(['pro_id'=>$data['pro_id'],'pur_price'=>$data['pur_price'],'amount'=>$data['amount'],'vendor_id'=>$stock['vendor_id'],'create_user'=>$this->user_session['id'],'selling_price'=>$stock['selling_price'],'type'=>2]);
            $result=$ProductPurHistory->save();
            if($result===false){
                return json(['code'=>1,'msg'=>'保存历史失败']);
            }
            $ProductClass->commit();
            return json(['code'=>0,'msg'=>'出库成功']);
        }catch (Exception $e){
            $ProductClass->rollback();
            trace($e->getMessage(),'error');
            return json(['code'=>1,'msg'=>'出库失败'.$e->getMessage()]);
        }
    }

    public function stockOutByGoodsIds(){
        $data=input('post.data/a');
        $ids=[];
        foreach ($data as $key=>$value){
            if(!isset($value['pro_id']) || !$value['pro_id']){
                return json(['code'=>1,'msg'=>$value['cn_name'].'商品不能为空']);
            }
            if(!is_numeric($value['amount'])){
                return json(['code'=>1,'msg'=>$value['cn_name'].'输入的不是数字']);
            }
            if(!isset($value['amount']) || !$value['amount']){
                return json(['code'=>1,'msg'=>$value['cn_name'].'出库数量必须大于0']);
            }
            if($value['type']===1){
                $isMatched=preg_match('/\D|^0/', $value['amount'], $matches);
                if($isMatched){
                    return json(['code'=>1,'msg'=>$value['cn_name'].'输入的数字不对']);
                }
            }
            $ids[]=$value['pro_id'];
        }
        $ProductClass=new Product();
        $ProductPurHistory=new ProductPurHistory();

        $stock=$ProductClass->where('id','in',$ids)->column('id,amount,locked_quantity,selling_price,pur_price,vendor_id','id');
        $product_history=[];
        foreach ($data as $key=>$value){
            $arr=&$stock[$value['pro_id']];
            if(round($arr['amount']-$arr['locked_quantity'],2)<$value['amount']){
                return json(['code'=>1,'msg'=>$value['cn_name'].'剩余可出库库存不足']);
            }
            $arr['amount'] -= $value['amount'];
            $product_history[]=['pro_id'=>$value['pro_id'],'pur_price'=>$arr['pur_price'],'amount'=>$value['amount'],'create_user'=>$this->user_session['id'],'selling_price'=>$arr['selling_price'],'type'=>2,'vendor_id'=>$arr['vendor_id']];
        }
        $ProductClass->startTrans();
        try{
            $result=$ProductClass->isUpdate(true)->allowField(['id','amount'])->saveAll($stock);
            if($result===false){
                return json(['code'=>1,'msg'=>'出库失败']);
            }
            $result=$ProductPurHistory->insertAll($product_history);
            if($result===false){
                return json(['code'=>1,'msg'=>'保存历史失败']);
            }
            $ProductClass->commit();
            return json(['code'=>0,'msg'=>'出库成功']);
        }catch (Exception $e){
            $ProductClass->rollback();
            trace($e->getMessage(),'error');
            return json(['code'=>1,'msg'=>'出库失败'.$e->getMessage()]);
        }
    }

    public function getStockOutList(){
        $type=input('post.type/d');
        $id=input('post.id');
        if($type===3){
            ['status'=>$status,'result'=>$result]=OrderItem::getOrderItemsByInvoice($id);
            if($status===false){
                return json(['code'=>1,'msg'=>$result,]);
            }
            return json(['code'=>0,'items'=>$result['items'],'order_id'=>$result['order_id']]);
        }elseif($type===1){
            ['status'=>$status,'result'=>$result]=OrderItem::getOrderItemsByWaybill($id);
            if($status===false){
                return json(['code'=>1,'msg'=>$result]);
            }
            return json(['code'=>0,'items'=>$result['items'],'waybill_id'=>$result['waybill_id']]);
        }
    }

    public function stockOutByInvoice()
    {
        $data=input('post.data/a');
        $type=input('post.type/d');

        $stock_out=[];
        $stock_pro_id=[];
        $order_ids=[];
        foreach ($data as $key=>$value){
            if(isset($value['children']) && !empty($value['children'])){
                $total_pur_price=0;
                foreach ($value['children'] as $item) {
                    if($item['type']===1){
                        $isMatched=preg_match('/\D|^0/', $item['stock_out_amount'], $matches);
                        if($isMatched){
                            return json(['code'=>1,'msg'=>$item['cn_name'].'输入的数字不对']);
                        }
                    }
                    $validate_result = $this->validate->scene('stock_out_invoice')->check($item);
                    if (!$validate_result) {
                        return json(['code' => 1, 'msg' => $value['order_id'].' '.$value['cn_name'].' '.$this->validate->getError()]);
                    }
                    if($item['stock_out_amount']<=0){
                        return json(['code'=>1,'msg'=>$item['show_index'].'出库数量必须大于0']);
                    }
                   $total_pur_price+=$item['pur_price']*$item['stock_out_amount'];
                }
                foreach ($value['children'] as $item) {
                    if($total_pur_price){
                        $selling_price=round($value['selling_price']*(($item['pur_price']*$item['stock_out_amount'])/$total_pur_price),2);
                    }else{
                        $selling_price=$value['selling_price'];
                    }
                    $stock_out[] = ['pro_id' => $item['pro_id'],'order_id'=>$value['order_id'],'id'=>$item['id'],'isChildren'=>1,'cn_name'=>$item['cn_name'],'show_index'=>$item['show_index'], 'pur_price' => $item['pur_price'], 'stock_out_amount' => $item['stock_out_amount'], 'type' => $item['type'],'selling_price'=>$selling_price,'order_item_id'=>$value['id']];
                    $stock_pro_id[]=$item['pro_id'];
                }
            }elseif($value['pro_id']){
                if($value['type']===1){
                    $isMatched=preg_match('/\D|^0/', $value['stock_out_amount'], $matches);
                    if($isMatched){
                        return json(['code'=>1,'msg'=>$value['cn_name'].'输入的数字不对']);
                    }
                }
                $validate_result = $this->validate->scene('stock_out_invoice')->check($value);
                if (!$validate_result) {
                    return json(['code' => 1, 'msg' =>$value['order_id'].' '.$value['cn_name'].' '.$this->validate->getError()]);
                }
                if($value['stock_out_amount']<=0){
                    return json(['code'=>1,'msg'=>$value['show_index'].'出库数量必须大于0']);
                }
                $stock_out[]=['pro_id'=>$value['pro_id'],'order_id'=>$value['order_id'],'isChildren'=>0,'id'=>$value['id'],'pur_price'=>$value['pur_price'],'stock_out_amount'=>$value['stock_out_amount'],'cn_name'=>$value['cn_name'],'show_index'=>$value['show_index'],'type'=>$value['type'],'order_item_id'=>$value['id'],'selling_price'=>$value['selling_price']];
                $stock_pro_id[]=$value['pro_id'];
            }
            $order_ids[] = $value['order_id'];
        }
        $order_id=array_unique($order_ids);
        ['status'=>$status,'result'=>$result]=Product::stockOutByInvoice($stock_out,$stock_pro_id,$order_id,$type);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function getStockHistoryParam(){
        ['status'=>$status,'result'=>$result]=StockWarehouse::getStockWarehouseList($this->user_session['group_id']);
        ['user_list'=>$user_list,'group_list'=>$group_list]=User::getUserList();
        $vendorList = Vendor::getVendorCompanyNameList();
        return json(['code'=>0,'stock_warehouse'=>$result['stock_warehouse'],'user_list'=>$user_list,'group_list'=>$group_list,'vendor_list'=>$vendorList]);
    }

    public function getStockHistoryList(){
        $page=input('post.pageIndex',1);
        $size=input('post.pageSize',10);
        $post=input('post.',[],'trim');
        $search_param=[
            'search_key'=>$post['search_key']??null,
            'search_value'=>$post['search_value']??null,
            'stock_warehouse'=>$post['warehouse']??null,
            'type'=>$post['type']??null,
            'vendor_id'=>$post['vendor_id']??null,
            'create_time'=>$post['create_time']??null,
            'group_id'=>$post['group_id']??null,
            'user_id'=>$post['user_id']??null,
        ];
        $page_param=[
            'page_num'=>$page,
            'page_size'=>$size,
        ];
        ['status'=>$status,'result'=>$result]=ProductPurHistory::getStockHistoryList($search_param,$page_param);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'product'=>$result['product'],'pageTotal'=>$result['total'],'action_role'=>$result['action_role']]);
    }
}